package top.lionkliu.filter;

import top.lionkliu.entity.User;

import javax.servlet.*;
import javax.servlet.annotation.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebFilter("/*")
public class LoginFilter implements Filter {
    public void init(FilterConfig config) throws ServletException {
    }

    public void destroy() {
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws ServletException, IOException {
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse res = (HttpServletResponse) response;
        //放行与登录z注册相关的资源的路径
        String[] urls = {"/login.jsp","/register.jsp","/register_success.jsp",
                "/static/","/errorPage/","/uploadFile/","/LoginServlet","/RegisterServlet","/VerifyCodeServlet"};

        String url = req.getRequestURL().toString();
        for (String s : urls) {
            if (url.contains(s)){
                //放行并退出方法体
                chain.doFilter(request, response);
                return;
            }
        }

        User loginUser = (User) req.getSession().getAttribute("loginUser");
        if (loginUser!=null){
            //登录了
            chain.doFilter(request, response);
        }else {
            req.getSession().setAttribute("login_msg","您尚未登录！");
            res.sendRedirect("/login.jsp");
            //req.setAttribute("login_msg","您尚未登录！");
            //req.getRequestDispatcher("/login.jsp").forward(request, response);
        }
    }
}
